import { useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import Creator from "../store/actions";
// 引入api
import CommsApi from "../api/comms";


export const useComms = () => {
    // 获取全部父类型数据
    const comms = useSelector(state => {
        return state.getAll
    })
    const dispatch = useDispatch();
    const { curPage, eachPage } = comms;
    // 操作状态的行为

    // 修改当前页
    const setCurPage = useCallback(curPage => {
        dispatch(Creator.setCurPage({ curPage }));
    }, [dispatch])

    // 修改每页显示条数
    const setEachPage = useCallback(eachPage => {
        dispatch(Creator.setEachPage({ eachPage }));
    }, [dispatch])

    // 获取所有商品
    const getComms = useCallback(async childId => {
        const data = await CommsApi.getAll({ curPage, eachPage, childId })
        console.log(data);
        dispatch(Creator.getAll(data));
    }, [curPage, eachPage, dispatch]);

    //添加商品
    const addComm = useCallback(async ({ name, count, price, childId, isAttend, desc, image }) => {
        const data = await CommsApi.add({ name, count, price, childId, isAttend, desc, image })
        return data
    }, []);

    //删除商品
    const delComm = useCallback(async (_id ) => {
        const data = await CommsApi.del({ _id })
        return data
    }, []);

    return [comms, { getComms, setCurPage, setEachPage, addComm,delComm }]

}